package com.taxx.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.taxx.common.Result;
import com.taxx.config.TaxReportConfig;
import com.taxx.entity.DataUploadRecord;
import com.taxx.entity.OperationLog;
import com.taxx.entity.TaxApiLog;
import com.taxx.service.SystemLogService;
import com.taxx.util.Sm4Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 系统日志控制器
 * 
 * @author taxx
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/system/logs")
@CrossOrigin
public class SystemLogController {

    @Autowired
    private SystemLogService systemLogService;

    @Autowired
    private TaxReportConfig taxReportConfig;

    /**
     * 获取数据导入日志
     */
    @GetMapping("/upload")
    public Result<Map<String, Object>> getDataImportLogs(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) String fileName,
            @RequestParam(required = false) String dataType,
            @RequestParam(required = false) Integer status) {

        try {
            IPage<DataUploadRecord> pageResult = systemLogService.getDataImportLogs(page, size, fileName, dataType, status);

            Map<String, Object> result = new HashMap<>();
            result.put("records", pageResult.getRecords());
            result.put("total", pageResult.getTotal());
            result.put("current", pageResult.getCurrent());
            result.put("size", pageResult.getSize());

            return Result.success("获取数据导入日志成功", result);
        } catch (Exception e) {
            log.error("获取数据导入日志失败", e);
            return Result.error("获取数据导入日志失败: " + e.getMessage());
        }
    }

    /**
     * 获取API调用日志
     */
    @GetMapping("/api")
    public Result<Map<String, Object>> getApiLogs(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) String apiName,
            @RequestParam(required = false) Integer status) {

        try {
            IPage<TaxApiLog> pageResult = systemLogService.getApiLogs(page, size, apiName, status);

            Map<String, Object> result = new HashMap<>();
            result.put("records", pageResult.getRecords());
            result.put("total", pageResult.getTotal());
            result.put("current", pageResult.getCurrent());
            result.put("size", pageResult.getSize());

            return Result.success("获取API调用日志成功", result);
        } catch (Exception e) {
            log.error("获取API调用日志失败", e);
            return Result.error("获取API调用日志失败: " + e.getMessage());
        }
    }

    /**
     * 获取操作日志
     */
    @GetMapping("/operation")
    public Result<Map<String, Object>> getOperationLogs(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String operation,
            @RequestParam(required = false) Integer status) {

        try {
            IPage<OperationLog> pageResult = systemLogService.getOperationLogs(page, size, username, operation, status);

            Map<String, Object> result = new HashMap<>();
            result.put("records", pageResult.getRecords());
            result.put("total", pageResult.getTotal());
            result.put("current", pageResult.getCurrent());
            result.put("size", pageResult.getSize());

            return Result.success("获取操作日志成功", result);
        } catch (Exception e) {
            log.error("获取操作日志失败", e);
            return Result.error("获取操作日志失败: " + e.getMessage());
        }
    }

    /**
     * 删除日志
     */
    @DeleteMapping("/{logType}/{logId}")
    public Result<String> deleteLog(@PathVariable String logType, @PathVariable Long logId) {
        try {
            boolean success = systemLogService.deleteLog(logId, logType);
            if (success) {
                return Result.success("删除日志成功");
            } else {
                return Result.error("删除日志失败");
            }
        } catch (Exception e) {
            log.error("删除日志失败, logType: {}, logId: {}", logType, logId, e);
            return Result.error("删除日志失败: " + e.getMessage());
        }
    }

    /**
     * 清空日志
     */
    @DeleteMapping("/{logType}/clear")
    public Result<String> clearLogs(@PathVariable String logType) {
        try {
            boolean success = systemLogService.clearLogs(logType);
            if (success) {
                return Result.success("清空日志成功");
            } else {
                return Result.error("清空日志失败");
            }
        } catch (Exception e) {
            log.error("清空日志失败, logType: {}", logType, e);
            return Result.error("清空日志失败: " + e.getMessage());
        }
    }

    /**
     * 导出日志
     */
    @GetMapping("/{logType}/export")
    public void exportLogs(@PathVariable String logType,
                            @RequestParam(defaultValue = "1") int page,
                            @RequestParam(defaultValue = "1000") int size,
                            @RequestParam(required = false) String fileName,
                            @RequestParam(required = false) String dataType,
                            @RequestParam(required = false) Integer status,
                            @RequestParam(required = false) String apiName,
                            @RequestParam(required = false) String username,
                            @RequestParam(required = false) String operation,
                            HttpServletResponse response) throws IOException {

        try {
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");

            String fileNameHeader = "";
            switch (logType) {
                case "upload":
                    fileNameHeader = "数据导入日志";
                    break;
                case "api":
                    fileNameHeader = "API调用日志";
                    break;
                case "operation":
                    fileNameHeader = "操作日志";
                    break;
                default:
                    fileNameHeader = "系统日志";
            }

            String fileNameEncoded = URLEncoder.encode(fileNameHeader + ".xlsx", StandardCharsets.UTF_8.toString());
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileNameEncoded);

            // TODO: 实现Excel导出逻辑
            // 这里可以使用EasyExcel或其他Excel库来导出数据

            log.info("导出日志成功, logType: {}", logType);

        } catch (Exception e) {
            log.error("导出日志失败, logType: {}", logType, e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("/decrypt")
    public Result<String> decrypt(@RequestBody Map<String,String> data) {
        String decrypt = Sm4Util.decryptWithSm4Ecb(data.get("data"), taxReportConfig.getPlatformSecret());
        return Result.success(decrypt);
    }
}
